<?php
/**
 * [WeEngine System] Copyright (c) 2014 WE7.CC
 * WeEngine is NOT a free software, it under the license terms, visited http://www.we7.cc/ for more details.
 */
defined('IN_IA') or exit('Access Denied');
define('IN_GW', true);

load()->model('message');
load()->model('utility');
if (!empty($_GPC['code'])) {
	
	if (!$_W['isajax']) {
		$_W['isw7_sign'] = true;
	}
	$accesstoken = cloud_oauth_token(safe_gpc_string($_GPC['code']));
	if (empty($accesstoken) || is_error($accesstoken)) {
		$message = '授权用户登录获取accesstoken失败，请联系管理员处理。详情：' . $accesstoken['message'];
		$_W['isajax'] ? iajax(-1, $message) : message($message, '', 'error');
	}
	$cloud_user_info = cloud_oauth_user($accesstoken['access_token']);
	if (is_error($cloud_user_info)) {
		$_W['isajax'] ? iajax(-1, $cloud_user_info['message']) : message($cloud_user_info['message'], '', 'error');
	}
	$bind_info = pdo_get('users_bind', ['bind_sign' => $cloud_user_info['openid'], 'third_type' => USER_REGISTER_TYPE_CONSOLE]);
	if (-1 == $cloud_user_info['out_uid'] || 'founder' == $cloud_user_info['role_identify']) {
		$user_id = -1 == $cloud_user_info['out_uid'] ? current(explode(',', $_W['config']['setting']['founder'])) : $cloud_user_info['out_uid'];
	} elseif (!empty($bind_info) && !empty($bind_info['uid'])) {
		$user_id = $bind_info['uid'];
	} elseif (!empty($cloud_user_info['out_uid'])) {
		$user_id = $cloud_user_info['out_uid'];
	} else {
		if (igetcookie('bind_console')) {
			isetcookie('__w7sign', '', -100);
			$_W['isajax'] ? iajax(-1, '请您先绑定系统原用户名和密码！', url('user/third-bind/console')) : message('请您先绑定系统原用户名和密码！', url('user/third-bind/console'), 'error');
		}
		$str = random(8);
		$user_info = [
			'username' => user_check(['username' => $cloud_user_info['username']]) ? ($cloud_user_info['username'] . random(4)) : $cloud_user_info['username'],
			'password' => $str,
			'repassword' => $str,
			'remark' => '',
			'starttime' => TIMESTAMP,
			'founder_groupid' => 0,
			'groupid' => empty($_W['setting']['register']['groupid']) ? 0 : safe_gpc_int($_W['setting']['register']['groupid']),
		];
		if (in_array($cloud_user_info['role_identify'], [ACCOUNT_MANAGE_NAME_VICE_FOUNDER_RULE])) {
			$user_info['founder_groupid'] = 2;
			$user_info['groupid'] = 0;
		}
		$user_save_result = user_info_save($user_info);
		if (is_error($user_save_result)) {
			message($user_save_result['message'], '', 'info');
		}
		pdo_insert('users_bind', ['uid' => $user_save_result['uid'], 'bind_sign' => $cloud_user_info['openid'], 'third_nickname' => $cloud_user_info['username'], 'third_type' => USER_REGISTER_TYPE_CONSOLE, 'third_uid' => $cloud_user_info['user_id']]);
		$user_id = $user_save_result['uid'];
	}
	
	$user_info = user_single($user_id);
	if (empty($user_info)) {
		$_W['isajax'] ? iajax(-1, '用户不存在，请联系管理员处理！') : message('用户不存在，请联系管理员处理！', '', 'error');
	}
	if (USER_STATUS_CHECK == $user_info['status'] || USER_STATUS_BAN == $user_info['status']) {
		$_W['isajax'] ? iajax(-1, '您的账号正在审核或是已经被系统禁止，请联系网站管理员解决') : message('您的账号正在审核或是已经被系统禁止，请联系网站管理员解决', '', 'error');
	}
	if ($_W['role'] == ACCOUNT_MANAGE_NAME_EXPIRED || $_W['highest_role'] == ACCOUNT_MANAGE_NAME_EXPIRED) {
		$_W['isajax'] ? iajax(-1, '您的账号已过期，请联系管理员处理！') : message('您的账号已过期，请联系管理员处理！', '', 'error');
	}
	$_W['uid'] = $user_info['uid'];
	$_W['isfounder'] = user_is_founder($_W['uid']);
	$_W['isadmin'] = user_is_founder($_W['uid'], true);
	$_W['user'] = $user_info;
	if (ACCOUNT_MANAGE_NAME_GENERAL_RULE == $cloud_user_info['role_identify'] && ACCOUNT_MANAGE_GROUP_VICE_FOUNDER == $user_info['founder_groupid']) {
		$result = cloud_bind_user_token(['access_token' => $accesstoken, 'out_user_id' => $user_id, 'role_identify' => 'role2']);
		if (is_error($result)) {
			message($result['message'], '', 'error');
		}
		message('您为副创始人，角色转变中，稍后请重新进入该站点', '', 'error');
	}
	if ($bind_info['third_nickname'] != $cloud_user_info['username'] || $bind_info['bind_sign '] != $cloud_user_info['openid'] || $bind_info['third_uid '] != $cloud_user_info['user_id']) {
		if (empty($bind_info)) {
			pdo_insert('users_bind', ['uid' => $user_id, 'bind_sign' => $cloud_user_info['openid'], 'third_nickname' => $cloud_user_info['username'], 'third_type' => USER_REGISTER_TYPE_CONSOLE, 'third_uid' => $cloud_user_info['user_id']]);
		} else {
			pdo_update('users_bind', ['third_nickname' => $cloud_user_info['username'], 'bind_sign' => $cloud_user_info['openid'], 'third_uid' => $cloud_user_info['user_id']], ['id' => $bind_info['id']]);
		}
	}
	$update_data = ['lastvisit' => TIMESTAMP, 'lastip' => $_W['clientip']];
	switch ($cloud_user_info['role_identify']) {
		case ACCOUNT_MANAGE_NAME_VICE_FOUNDER_RULE:
			$update_data['founder_groupid'] = 2;
			break;
		case ACCOUNT_MANAGE_NAME_GENERAL_RULE:
			$update_data['founder_groupid'] = 0;
			break;
	}
	pdo_update('users', $update_data, ['uid' => $user_info['uid']]);
	$w7_user_token = authcode(json_encode([
		'uid' => $user_info['uid'],
		'hash' => !empty($user_info['hash']) ? $user_info['hash'] : md5($user_info['password'] . $user_info['salt'])
	]), 'encode');
	if (isset($_W['setting']['copyright']['log_status']) && $_W['setting']['copyright']['log_status'] == STATUS_ON) {
		$local = get_position_by_ip();
		if (is_error($local)) {
			if ($_W['isajax']) {
				iajax(-1, $local['message']);
			}
			message($local['message'], '', 'error');
		}
		$local['data']['city'] = str_replace('市', '', $local['data']['city']);
		$login_log = [
			'uid' => $user_info['uid'],
			'ip' => $_W['clientip'],
			'city' => isset($local['data']['city']) ? $local['data']['city'] : '',
			'createtime' => TIMESTAMP
		];
		table('users_login_logs')->fill($login_log)->save();
	}
	isetcookie('__w7sign', $w7_user_token);
	isetcookie('__session', $w7_user_token);
	$forward = user_login_forward($_GPC['redirect']);
	iajax(0, $w7_user_token, $forward);
}
$_GPC['login_type'] = !empty($_GPC['login_type']) ? $_GPC['login_type'] : 'system';
$support_login_types = OAuth2Client::supportThirdLoginType();
if (checksubmit() || $_W['isajax'] || in_array($_GPC['login_type'], $support_login_types)) {
	if ($_W['isajax'] && STATUS_OFF == $_W['ishttps'] && empty($_W['setting']['copyright']['local_install'])) {
		iajax(-1, '该站点没有配置https，该功能无法正常使用，请联系站点管理员处理。');
	}
	_login($_GPC['referer']);
}

$setting = $_W['setting'];
$w7_oauth_login = !empty($_GPC['w7_oauth_login']) ? STATUS_ON : STATUS_OFF;
if (!$w7_oauth_login) {
	die(ierror_page('违规操作，即将跳转首页...', $_W['siteroot']));
}
$login_urls = user_support_urls();
$login_template = (!empty($_W['setting']['basic']['login_template']) && !$w7_oauth_login) ? $_W['setting']['basic']['login_template'] : 'base';
template('user/login-' . $login_template);

function _login($forward = '') {
	global $_GPC, $_W;
	if (empty($_GPC['login_type'])) {
		$_GPC['login_type'] = 'system';
	}

	if (empty($_GPC['handle_type'])) {
		$_GPC['handle_type'] = 'login';
	}

	if ('login' == $_GPC['handle_type']) {
		$member = OAuth2Client::create($_GPC['login_type'], $_W['setting']['thirdlogin'][$_GPC['login_type']]['appid'], $_W['setting']['thirdlogin'][$_GPC['login_type']]['appsecret'])->login();
	} else {
		$member = OAuth2Client::create($_GPC['login_type'], $_W['setting']['thirdlogin'][$_GPC['login_type']]['appid'], $_W['setting']['thirdlogin'][$_GPC['login_type']]['appsecret'])->bind();
	}

	if (!empty($_W['user']) && '' != $_GPC['handle_type'] && 'bind' == $_GPC['handle_type']) {
		if (is_error($member)) {
			if ($_W['isajax']) {
				iajax(-1, $member['message'], url('user/profile/bind'));
			}
			itoast($member['message'], url('user/profile/bind'), '');
		} else {
			if ($_W['isajax']) {
				iajax(1, '绑定成功', url('user/profile/bind'));
			}
			itoast('绑定成功', url('user/profile/bind'), '');
		}
	}

	if (is_error($member)) {
		if ($_W['isajax']) {
			iajax(-1, $member['message'], url('user/login'));
		}
		itoast($member['message'], url('user/login'), '');
	}

	$record = user_single($member);
	$failed = pdo_get('users_failed_login', ['username' => safe_gpc_string($_GPC['username'])]);
	if (!empty($record)) {
		if (USER_STATUS_CHECK == $record['status'] || USER_STATUS_BAN == $record['status']) {
			if ($_W['isajax']) {
				iajax(-1, '您的账号正在审核或是已经被系统禁止，请联系网站管理员解决');
			}
			itoast('您的账号正在审核或是已经被系统禁止，请联系网站管理员解决', url('user/login'), '');
		}
		$_W['uid'] = $record['uid'];
		$_W['isfounder'] = user_is_founder($record['uid']);
		$_W['isadmin'] = user_is_founder($_W['uid'], true);
		$_W['user'] = $record;

		$support_login_bind_types = Oauth2CLient::supportThirdLoginBindType();
		if (in_array($_GPC['login_type'], $support_login_bind_types) && !empty($_W['setting']['copyright']['oauth_bind']) && !$record['is_bind'] && empty($_W['isfounder']) && (USER_REGISTER_TYPE_QQ == $record['register_type'] || USER_REGISTER_TYPE_WECHAT == $record['register_type'])) {
			if ($_W['isajax']) {
				iajax(-1, '您还没有注册账号，请前往注册');
			}
			message('您还没有注册账号，请前往注册', url('user/third-bind/bind_oauth', ['uid' => $record['uid'], 'openid' => $record['openid'], 'register_type' => $record['register_type']]));
			exit;
		}

		if (!empty($_W['siteclose']) && empty($_W['isfounder'])) {
			if ($_W['isajax']) {
				iajax(-1, '站点已关闭，关闭原因:' . $_W['setting']['copyright']['reason']);
			}
			itoast('站点已关闭，关闭原因:' . $_W['setting']['copyright']['reason'], '', '');
		}
		if (isset($_W['setting']['copyright']['log_status']) && $_W['setting']['copyright']['log_status'] == STATUS_ON) {
			$login_log = [
				'uid' => $_W['uid'],
				'ip' => $_W['clientip'],
				'city' => isset($local['data']['city']) ? $local['data']['city'] : '',
				'createtime' => TIMESTAMP
			];
			table('users_login_logs')->fill($login_log)->save();
		}
		
		
			if ((empty($_W['isfounder']) || user_is_vice_founder()) && $_W['user']['is_expired']) {
				$user_expire = setting_load('user_expire');
				$user_expire = !empty($user_expire['user_expire']) ? $user_expire['user_expire'] : [];
				$notice = !empty($user_expire['notice']) ? $user_expire['notice'] : '您的账号已到期，请联系管理员!';
				if ($_W['isajax']) {
					iajax(-1, $notice);
				}
				message($notice);
			}
		

		$cookie = [
			'uid' => $record['uid'],
			'lastvisit' => $record['lastvisit'],
			'lastip' => $record['lastip'],
			'hash' => !empty($record['hash']) ? $record['hash'] : md5($record['password'] . $record['salt']),
			'rember' => safe_gpc_int($_GPC['rember']),
		];
		$session = authcode(json_encode($cookie), 'encode');
		isetcookie('__session', $session, !empty($_GPC['rember']) ? 7 * 86400 : 0, true);
		pdo_update('users', ['lastvisit' => TIMESTAMP, 'lastip' => $_W['clientip']], ['uid' => $record['uid']]);
		
		$forward = safe_gpc_url($forward);
		$code = random(18);
		$cache_key = cache_system_key('console_oauth_code', ['code' => $code]);
		cache_write($cache_key, $record['uid'], CACHE_EXPIRE_SHORT);
		if (!empty($forward)) {
			$forward .= (parse_url($forward, PHP_URL_QUERY) ? '&' : '?') . 'code=' . $code;
		}
		$forward = !empty($forward) ? $forward : user_login_forward();
		if ($record['uid'] != $_GPC['__uid']) {
			isetcookie('__uniacid', '', -7 * 86400);
			isetcookie('__uid', '', -7 * 86400);
		}
		if (!empty($failed)) {
			pdo_delete('users_failed_login', ['id' => $failed['id']]);
		}
		if ($_W['isajax']) {
			iajax(0, "欢迎回来，{$record['username']}", $forward);
		}
		itoast("欢迎回来，{$record['username']}", $forward, 'success');
	} else {
		if (empty($failed)) {
			pdo_insert('users_failed_login', ['ip' => $_W['clientip'], 'username' => safe_gpc_string($_GPC['username']), 'count' => '1', 'lastupdate' => TIMESTAMP]);
		} else {
			pdo_update('users_failed_login', ['count' => $failed['count'] + 1, 'lastupdate' => TIMESTAMP], ['id' => $failed['id']]);
		}
		if ($_W['isajax']) {
			iajax(-1, '登录失败，请检查您输入的账号和密码');
		}
		itoast('登录失败，请检查您输入的账号和密码', '', '');
	}
}
